package org.zjx.swing.view;

import lombok.Data;
import lombok.EqualsAndHashCode;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionListener;

@EqualsAndHashCode(callSuper = true)
@Data
public class LoginView extends JFrame {
    private JTextField usernameField;
    private JPasswordField passwordField;
    private JButton confirmButton;
    private JButton cancelButton;
    private static final Font LABEL_FONT = new Font("微软雅黑", Font.PLAIN, 32);
    private static final Font FIELD_FONT = new Font("宋体", Font.PLAIN, 32);
    private static final Font BUTTON_FONT = new Font("微软雅黑", Font.BOLD, 32);

    public LoginView() {
        // 设置全局字体前先初始化组件
        setTitle("登录界面");
        setSize(400, 400);

        // 创建主面板和背景
        JPanel mainPanel = new JPanel(new GridBagLayout());
        GridBagConstraints gbc = new GridBagConstraints();
        gbc.insets = new Insets(5, 5, 5, 5);

        // 添加用户名标签和输入框
        JLabel usernameLabel = new JLabel("用户名:");
        gbc.gridx = 0;
        gbc.gridy = 0;
        mainPanel.add(usernameLabel, gbc);
        usernameField = new JTextField(15);
        gbc.gridx = 1;
        mainPanel.add(usernameField, gbc);
        usernameLabel.setFont(LABEL_FONT);
        usernameField.setFont(FIELD_FONT);

        // 添加密码标签和输入框
        JLabel passwordLabel = new JLabel("密码:");
        gbc.gridx = 0;
        gbc.gridy = 1;
        mainPanel.add(passwordLabel, gbc);
        passwordField = new JPasswordField(15);
        gbc.gridx = 1;
        mainPanel.add(passwordField, gbc);
        passwordLabel.setFont(LABEL_FONT);
        passwordField.setFont(FIELD_FONT);

        // 按钮面板
        JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT,20, 15));
        confirmButton = new JButton("确认");
        cancelButton = new JButton("取消");
        confirmButton.setFont(BUTTON_FONT);
        cancelButton.setFont(BUTTON_FONT);

        buttonPanel.add(confirmButton);
        buttonPanel.add(cancelButton);

        add(mainPanel, BorderLayout.CENTER);
        add(buttonPanel, BorderLayout.SOUTH);

        getRootPane().setDefaultButton(confirmButton);
    }

    public String getUsername() {
        return usernameField.getText();
    }

    public String getPassword() {
        return new String(passwordField.getPassword());
    }

    public void setConfirmButtonListener(ActionListener listener) {
        confirmButton.addActionListener(listener);
    }

    public void setCancelButtonListener(ActionListener listener) {
        cancelButton.addActionListener(listener);
    }

    public void showErrorMessage(String message) {
        JOptionPane.showMessageDialog(this, message, "错误", JOptionPane.ERROR_MESSAGE);
    }

    public void clearFields() {
        usernameField.setText("");
        passwordField.setText("");
    }
}
